package org.zwd.computePrice.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.zwd.computePrice.domain.Crab;


public class CrabDao {
	public List<Crab> loadAll(){
		List<Crab> crabList = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			crabList = new ArrayList<Crab>();
			conn = DBUtils.getConnection();
			String sql = "select id,name,ismale from cp_crab";
			
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			
			while(rs.next()){
				Crab crab = new Crab();
				crab.setId(rs.getInt(1));
				crab.setName(rs.getString(2));
				crab.setIsmale(rs.getInt(3));
				crabList.add(crab);
			}
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		finally {
			DBUtils.free(rs, pstmt, conn);
		}
		return crabList;
	}
	
	public Crab findCrabById(int id){
		Crab crab = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			conn = DBUtils.getConnection();
			String sql = "select id,name,ismale from cp_crab where id=?";
			
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, id);
			rs = pstmt.executeQuery();
			
			if(rs.next()){
				crab = new Crab();
				crab.setId(rs.getInt(1));
				crab.setName(rs.getString(2));
				crab.setIsmale(rs.getInt(3));
			}
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		finally {
			DBUtils.free(rs, pstmt, conn);
		}
		return crab;
	}
	
}
